﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Corrmirt
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public class typePort
        {
            public int ID { get; set; }
            public string type { get; set; }
        }
        pase Pase = new pase();
        public void pase_json()
        {
            string text = System.IO.File.ReadAllText(System.IO.Directory.GetCurrentDirectory() + @".\user.json");
            Console.WriteLine(text);
            JArray jsons = JArray.Parse(text);
            for (int i = 0; i < jsons.Count; i++)
            {
                Console.WriteLine(jsons[i]);
            }
        }
        public bool IsClosed { get; set; } = false;
        public MainWindow()
        {
            Closed += MyWindow_Closed;
            InitializeComponent();
            
            List<typePort> list = new List<typePort>();
            list.Add(new typePort { ID = 1, type = "tcp" });
            list.Add(new typePort { ID = 1, type = "udp" });
            Comboxu_type.ItemsSource = list;
            //检验
            Pase.verification();
            list_clanin();
            //Pase.Read_ini("\\ip.ini");
            Pase.frp_ini();
        }
        //检测到窗口关闭
        private void MyWindow_Closed(object sender, EventArgs e)
        {
            foreach (var process in Process.GetProcessesByName("frpc"))
            {
                try
                {
                    // 杀掉这个进程。
                    process.Kill();

                    // 等待进程被杀掉。你也可以在这里加上一个超时时间（毫秒整数）。
                    process.WaitForExit();
                }
                catch (InvalidOperationException)
                {

                }
            }
            IsClosed = true;
        }
        // 重新添加组件
        public void list_clanin()
        {
            JArray jsons = Pase.pase_json();
            Type_List.Children.Clear();
            if (jsons != null)
            {
                for (int i = 0; i < jsons.Count; i++)
                {
                    //System.Diagnostics.Debug.WriteLine(Pase.pase_json()[i]);
                    UserControl1 userControls1 = new UserControl1();
                    userControls1.Margin = new Thickness(8, 8, 8, 8);
                    userControls1.close_port.Tag = i;
                    userControls1.close_port.MouseLeftButtonUp += del_close_port_MouseLeftButtonDown; 
                    string iptexts = "映射: " + jsons[i]["local_ip"].ToString() + jsons[i]["local_port"].ToString() + " \r\n外网: "+ Pase.Read_ini("\\ip.ini")+":" + jsons[i]["Outside_Port"].ToString();
                    userControls1.iptext.Text = iptexts;
                    Type_List.Children.Add(userControls1);
                }
            }
            //Pase.Run_frp();
            jsons = null;
        }
        // 删除隧道
        private void del_close_port_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MaterialDesignThemes.Wpf.PackIcon btn = (MaterialDesignThemes.Wpf.PackIcon)sender;
            Pase.move_json(btn.Tag.ToString());
            list_clanin();
            foreach (var process in Process.GetProcessesByName("frpc"))
            {
                try
                {
                    // 杀掉这个进程。
                    process.Kill();

                    // 等待进程被杀掉。你也可以在这里加上一个超时时间（毫秒整数）。
                    process.WaitForExit();
                }
                catch (InvalidOperationException)
                {

                }
            }
            frp_play_StopCircle.Visibility = Visibility.Hidden;
            frp_play.Visibility = Visibility.Visible;
        }

        //隧道添加按钮
        private void Add_type_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (Comboxu_type.Text == string.Empty || local_ip.Text == string.Empty || local_port.Text == string.Empty || Outside_Port.Text == string.Empty) {
                MessageBox.Show("Textbox text in None!");
            }
            else
            {
                Pase.generate_wtire_json(Pase.generate_json(
                Guid.NewGuid().ToString(),
                Comboxu_type.Text,
                local_ip.Text,
                local_port.Text,
                Outside_Port.Text
             ));
                local_ip.Text = local_port.Text = Outside_Port.Text = string.Empty;
                Comboxu_type.SelectedIndex = -1;
                Add_xite.Visibility = Visibility.Hidden;
            }
            list_clanin();
        }
        //取消隧道确定
        private void PackIcon_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            local_ip.Text = local_port.Text = Outside_Port.Text = string.Empty;
            Comboxu_type.SelectedIndex = -1;
            Add_xite.Visibility = Visibility.Hidden;
        }
        //显示输入隧道窗口
        private void add_typecs_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Add_xite.Visibility = Visibility.Visible;
        }
        //开启FRP
        private void frp_play_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {            
            Pase.Run_frp();
            frp_play.Visibility = Visibility.Hidden;
            frp_play_StopCircle.Visibility = Visibility.Visible;
        }
        //关闭FRP
        private void frp_play_StopCircle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            foreach (var process in Process.GetProcessesByName("frpc"))
            {
                try
                {
                    // 杀掉这个进程。
                    process.Kill();

                    // 等待进程被杀掉。你也可以在这里加上一个超时时间（毫秒整数）。
                    process.WaitForExit();
                }
                catch (InvalidOperationException)
                {

                }
            }
            frp_play_StopCircle.Visibility = Visibility.Hidden;
            frp_play.Visibility = Visibility.Visible;
        }
    }
}
